#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
实时YASA分析结果分析脚本

该脚本用于分析实时YASA分析的结果，包括：
1. 读取JSON格式的分析结果
2. 分析每次分析的趋势变化
3. 计算置信度变化趋势
4. 分析睡眠阶段分布的变化
5. 生成可视化图表

使用方法：
    python analyze_realtime_results.py
"""

import json
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime
import os

def load_realtime_results(json_file):
    """加载实时分析结果"""
    with open(json_file, 'r', encoding='utf-8') as f:
        data = json.load(f)
    return data

def analyze_trends(data):
    """分析趋势变化"""
    results = data['analysis_results']
    
    # 提取数据
    analysis_indices = [r['analysis_index'] for r in results]
    data_seconds = [r['data_seconds'] for r in results]
    data_points = [r['data_points'] for r in results]
    sampling_rates = [r['sampling_rate'] for r in results]
    total_epochs = [r['total_epochs'] for r in results]
    avg_confidences = [r['avg_confidence'] for r in results]
    
    # 睡眠阶段分布
    stage_distributions = []
    for r in results:
        stage_distributions.append(r['stage_distribution'])
    
    return {
        'analysis_indices': analysis_indices,
        'data_seconds': data_seconds,
        'data_points': data_points,
        'sampling_rates': sampling_rates,
        'total_epochs': total_epochs,
        'avg_confidences': avg_confidences,
        'stage_distributions': stage_distributions
    }

def print_summary(data, trends):
    """打印分析摘要"""
    print("=" * 60)
    print("实时YASA分析结果摘要")
    print("=" * 60)
    
    # 基本信息
    sim_info = data['simulation_info']
    print(f"数据文件: {sim_info['csv_file']}")
    print(f"总处理时长: {sim_info['total_seconds_processed']} 秒")
    print(f"总数据点数: {sim_info['total_data_points']:,}")
    print(f"最小分析时长: {sim_info['min_analysis_seconds']} 秒")
    print(f"总分析次数: {sim_info['total_analyses']}")
    print()
    
    # 趋势分析
    print("趋势分析:")
    print("-" * 40)
    
    # 置信度趋势
    confidences = trends['avg_confidences']
    print(f"置信度变化:")
    print(f"  初始置信度: {confidences[0]:.2f}%")
    print(f"  最终置信度: {confidences[-1]:.2f}%")
    print(f"  置信度变化: {confidences[-1] - confidences[0]:.2f}%")
    print(f"  最高置信度: {max(confidences):.2f}%")
    print(f"  最低置信度: {min(confidences):.2f}%")
    print()
    
    # 采样率变化
    sampling_rates = trends['sampling_rates']
    print(f"采样率变化:")
    print(f"  初始采样率: {sampling_rates[0]:.2f} Hz")
    print(f"  最终采样率: {sampling_rates[-1]:.2f} Hz")
    print(f"  平均采样率: {np.mean(sampling_rates):.2f} Hz")
    print()
    
    # 睡眠阶段分析
    print("睡眠阶段分布变化:")
    print("-" * 40)
    stages = ['Wake', 'N1', 'N2', 'N3', 'REM']
    
    for i, dist in enumerate(trends['stage_distributions']):
        total_epochs = sum(dist.values())
        print(f"分析 #{i+1} (数据时长: {trends['data_seconds'][i]}秒, 总时期: {total_epochs}):")
        for stage in stages:
            count = dist.get(stage, 0)
            percentage = (count / total_epochs * 100) if total_epochs > 0 else 0
            print(f"  {stage}: {count} ({percentage:.1f}%)")
        print()

def create_visualizations(trends, output_dir="test"):
    """创建可视化图表"""
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    # 设置中文字体
    plt.rcParams['font.sans-serif'] = ['SimHei', 'DejaVu Sans']
    plt.rcParams['axes.unicode_minus'] = False
    
    # 1. 置信度变化趋势
    plt.figure(figsize=(12, 8))
    
    plt.subplot(2, 2, 1)
    plt.plot(trends['data_seconds'], trends['avg_confidences'], 'b-o', linewidth=2, markersize=6)
    plt.title('置信度变化趋势')
    plt.xlabel('累积数据时长 (秒)')
    plt.ylabel('平均置信度 (%)')
    plt.grid(True, alpha=0.3)
    
    # 2. 数据点数变化
    plt.subplot(2, 2, 2)
    plt.plot(trends['data_seconds'], trends['data_points'], 'g-s', linewidth=2, markersize=6)
    plt.title('数据点数变化')
    plt.xlabel('累积数据时长 (秒)')
    plt.ylabel('数据点数')
    plt.grid(True, alpha=0.3)
    
    # 3. 采样率变化
    plt.subplot(2, 2, 3)
    plt.plot(trends['data_seconds'], trends['sampling_rates'], 'r-^', linewidth=2, markersize=6)
    plt.title('采样率变化')
    plt.xlabel('累积数据时长 (秒)')
    plt.ylabel('采样率 (Hz)')
    plt.grid(True, alpha=0.3)
    
    # 4. 总时期数变化
    plt.subplot(2, 2, 4)
    plt.plot(trends['data_seconds'], trends['total_epochs'], 'm-d', linewidth=2, markersize=6)
    plt.title('分析时期数变化')
    plt.xlabel('累积数据时长 (秒)')
    plt.ylabel('总时期数')
    plt.grid(True, alpha=0.3)
    
    plt.tight_layout()
    plt.savefig(f'{output_dir}/realtime_yasa_trends.png', dpi=300, bbox_inches='tight')
    plt.show()
    
    # 5. 睡眠阶段分布堆叠图
    plt.figure(figsize=(12, 6))
    
    stages = ['Wake', 'N1', 'N2', 'N3', 'REM']
    colors = ['red', 'orange', 'blue', 'green', 'purple']
    
    # 准备数据
    stage_data = {stage: [] for stage in stages}
    for dist in trends['stage_distributions']:
        for stage in stages:
            stage_data[stage].append(dist.get(stage, 0))
    
    # 创建堆叠图
    bottom = np.zeros(len(trends['data_seconds']))
    for i, stage in enumerate(stages):
        plt.bar(trends['data_seconds'], stage_data[stage], 
                bottom=bottom, label=stage, color=colors[i], alpha=0.8)
        bottom += stage_data[stage]
    
    plt.title('睡眠阶段分布变化')
    plt.xlabel('累积数据时长 (秒)')
    plt.ylabel('时期数')
    plt.legend()
    plt.grid(True, alpha=0.3)
    
    plt.tight_layout()
    plt.savefig(f'{output_dir}/realtime_yasa_stages.png', dpi=300, bbox_inches='tight')
    plt.show()

def main():
    """主函数"""
    # 查找最新的结果文件
    json_files = [f for f in os.listdir('.') if f.startswith('realtime_yasa_results_') and f.endswith('.json')]
    if not json_files:
        print("未找到实时YASA分析结果文件")
        return
    
    # 使用最新的文件
    latest_file = sorted(json_files)[-1]
    print(f"分析文件: {latest_file}")
    print()
    
    # 加载和分析数据
    data = load_realtime_results(latest_file)
    trends = analyze_trends(data)
    
    # 打印摘要
    print_summary(data, trends)
    
    # 创建可视化
    print("正在生成可视化图表...")
    create_visualizations(trends)
    print("分析完成！图表已保存到 test/ 目录")

if __name__ == "__main__":
    main()